%This script produces the adjustment vectors for the share matrices used to
%compute the IVs in estimation under each alternative calibration in Figure 6
%Corresponding author: Rodrigo Adao
%Date: 09/11/2024
%Input: model_data_fgkk.mat

%% Preliminaries
clear;
close all;

%set lacal paths
function_path = "..\Functions\";
addpath(function_path,'-frozen');
set_local_paths;

%Parameter grid
omega_star_grid = [linspace(0,5,11)   , 0*ones(1,10)      ,   0*ones(1,10)         ];
sigma_star_grid = [1.04*ones(1,11)    , linspace(1.5,6,10),   1.04*ones(1,10)      ];
sigma_grid      = [2.53*ones(1,11)    , 2.53*ones(1,10)   ,   1.1, linspace(4,16,9)];

%Define vector of large varieties in our sample
trade_target = 0.9;

%specify cluster and sample
test_cluster_grid = 1; %no clustering

Nspec = length(sigma_grid);

for j = 1:Nspec

display('------------- running new j -----------------')
    j
    
%% Import data

%estimation parameters
test_cluster = 1;   

%Model parameters
omega_star = omega_star_grid(j);
sigma_star = sigma_star_grid(j);
sigma      = sigma_grid(j);

%Run preliminary steps for estimation
estimation_preliminary_steps;
         
%% Shares

%Compute MC times share_sharep
tic

    shareMOD_dW_T = shareMOD_dW'; 
    share_sharep = zeros(Nobs, Nobs);
    MC_share_sharep = zeros(Nobs,Nobs);
    
    MCterm3 = eye(Nobs) ;
    
    Nobs
   parfor s=1:Nobs 
        auxT = shareMOD_dW_T(:,s);
        aux0 = shareMOD_dW*auxT;
        share_sharep(:,s) = aux0;
   
        %controls 
        aux1 = MC_term1(:,s);
        MC_term2=C*aux1;
        aux2= MCterm3(:,s)  - MC_term2;
        MC_share_sharep(:,s) = aux2.*aux0;
   end
toc

%Compute welfare adjustment vector
tic
    %Weighted
    omega_share = adjGE_const*(ww_dW.*shareMOD_dWbar);
    adjGE_wMC = MC_share_sharep\omega_share;
toc    

%output to save
save(save_share_path + "estimation_shares_t" + trade_target + "_s" + sigma + "_o" + omega_star + "_ss" + sigma_star +  ".mat", 'adjGE_wMC', 'trade_target')

end
